using System;
using System.Collections.Generic;
using DaphneTranslator.BusinessLogic;
using Gtk;

namespace DaphneTranslator
{
	
	
	public partial class NewRecordWidget : Gtk.Dialog
	{
		private DataGrid _dataGrid;
		private List<NewRecordValue> _recList;
		
		public NewRecordWidget ()
		{
			this.Build ();					
			
			_recList = new List<NewRecordValue> ();					
			
			// create columns
			_dataGrid = new DataGrid ();
			_dataGrid.Visible = true;
			_dataGrid.SetColumnCount (2);
			_dataGrid.AppendColumn (_dataGrid.CreateColumn (0, "Culture", "Culture", "#C8BFE7"));
			_dataGrid.AppendColumn (_dataGrid.CreateColumn (1, "LanguageText", "LanguageText", "#C8BFE7", true));
			vboxDataGrid.Add (_dataGrid);
			vboxDataGrid.ShowAll ();
								
			buttonCancel.Clicked += HandleCancelClick;
			buttonOk.Clicked += HandleOKClick;
		}


		void HandleOKClick (object sender, EventArgs e)
		{
			if (ValidateDialog () == false) {
				return;
			}
			Respond (ResponseType.Accept);			
		}

		void HandleCancelClick (object sender, EventArgs e)
		{
			Respond (ResponseType.Cancel);
		}
		
		public void SetLanguages (List<CultureRecord> lstLangs)
		{
			BuildDataGrid (lstLangs);
		}
		
		public Dictionary<string, string> GetData ()
		{
			Dictionary<string, string> dic = new Dictionary<string, string> ();
			// save entries
			dic [RecordKeys.Key] = entryTextKey.Text.Trim ();
			dic [RecordKeys.XmlNodeValue] = entryXmlNodeValue.Text.Trim ();
			
			// save cultures in datagrid
			foreach (var item in _recList) {
				dic [item.Culture] = item.LanguageText;
			}
			
			return dic;						
		}
		
		private void BuildDataGrid (List<CultureRecord> lstLangs)
		{		
			// create records
			_recList.Clear ();
			foreach (var lang in lstLangs) {
				NewRecordValue rec = new NewRecordValue ();
				rec.Culture = lang.Culture;
				rec.LanguageText = string.Empty;
				_recList.Add (rec);
			}
			
			// bind it
			_dataGrid.DataSource = _recList;
			_dataGrid.DataBind ();						
		}
		
		private void ShowValidationMessageBox (string sMessage)
		{
			MessageDialog msg = new MessageDialog (this, DialogFlags.Modal, MessageType.Warning,
				                                      ButtonsType.Ok, sMessage);
			msg.Title = "Validation error";
			msg.Run ();		
			msg.Destroy ();						
		}
		
		private bool ValidateDialog ()
		{
			if (string.IsNullOrWhiteSpace (entryTextKey.Text) == true) {
				ShowValidationMessageBox ("Please fill in the key of the new text record.");
				return false;
			}
			
			if (string.IsNullOrWhiteSpace (entryXmlNodeValue.Text) == true) {
				ShowValidationMessageBox ("Please fill in the XML node attribute value of the text.");
				return false;
			}								
			
			return true;
		}	
	}
	
	public class NewRecordValue
	{
		public string Culture
		{ get; set; }
		
		public string LanguageText
		{ get; set; }
	}
	
}

